<?php
namespace app\commands;
use app\components\Func;
use app\models\AuthAccount;
use app\models\PayOrder;
use app\models\AuthItem;
use yii\console\Application;
use yii\console\Controller;
use Workerman\Worker;
use Yii;

defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require dirname(__DIR__) . '/vendor/autoload.php';
require dirname(__DIR__) . '/vendor/yiisoft/yii2/Yii.php';

$config = require dirname(__DIR__) . '/config/console.php';

$application = new Application($config);
$application->init();

// 注意：这里与上个例子不同，使用的是websocket协议
$ws_worker = new Worker("websocket://127.0.0.1:8282");

// 启动4个进程对外提供服务
$ws_worker->count = 4;

// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function($connection, $data)
{
    $arr = json_decode($data,1);
    $func = $arr['func']??'';
    $obj = new WorkermanWebSocketController();
    if(!method_exists($obj,$func)){
        $func = 'getNewMsg';
    }
    $res = call_user_func_array([$obj,$func],[$arr['paras']]);
    // 向客户端发送hello $data
    $connection->send($res);
};
// 运行worker
Worker::runAll();


class WorkermanWebSocketController
{
    //获取新消息
    public function getNewMsg(array $arr){
        return $this->success([
            'new_comment'=>AuthAccount::fetchNewMsg($arr['uid'],AuthAccount::NEW_MSG_TYPE_COMMENT),
            'new_msg'=>AuthAccount::fetchNewMsg($arr['uid'],AuthAccount::NEW_MSG_TYPE_MESSAGE),
        ]);
    }
    //获取支付订单状态
    public function getPayOrderState(array $arr){
        $payOrder = PayOrder::findOne($arr['pay_order_id']);
        if(empty($payOrder)){
            return $this->success(['state'=>PayOrder::PAY_WAIT]);
        }
        return $this->success([
            'state'=>$payOrder->state,
        ]);
    }
    //统一报错AJAX
    public function error(\Throwable $e){
        $errmsg = $e->getMessage();
        if(YII_DEBUG){
            $errmsg.=$e->getFile().$e->getLine();
        }
        else{
            Yii::error($errmsg.$e->getFile().$e->getLine());
        }
        echo json_encode(['errcode'=>$e->getCode(),'errmsg'=>$errmsg],JSON_UNESCAPED_UNICODE);
//        return json_encode(['errcode'=>$e->getCode(),'errmsg'=>$errmsg],JSON_UNESCAPED_UNICODE);
    }
    //统一成功JAX
    public function success($arr = []){

//        header("Access-Control-Allow-Origin: *");
//        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
//        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        return json_encode(array_merge(['errcode'=>0,'errmsg'=>'','result'=>$arr]),JSON_UNESCAPED_UNICODE);
    }

}